import {
  getProcessTypeIdList,
  getProcessPropertyList,
  getYesOrNotList,
  getReportModelList,
  getLineCodeList,
  getLineCodeListNew,
  getstationsByLineCode,
} from "@/api/process/mesProcess";
import { checkStr, uniqueKey } from "@/utils/judge";
import url from "@/axios/url";
const { mesUrl } = url();
let vm = null;
const sendThis = (_this) => {
  vm = _this;
};
export { sendThis };
import excelUpload from "@/components/excel-upload/excelUpload";
import { exportUrl, exportCellUrl } from "@/api/process/mesProcess";
// 列表头按钮配置
export const operateList = {
  data () {
    const _this = this;
    return {
      operateList: [
        {
          name: $i18n.t("common.export"),
          type: "primary",
          icon: "el-icon-download",
          handleName: "export", //点击时返回的标识
          url: exportUrl,
          //auth: "auth:operlog:export", //权限字段
        },
        {
          name: $i18n.t("common.add"),
          type: "primary",
          icon: "el-icon-circle-plus-outline",
          handleName: "add", // 点击时返回的标识
        },
        {
          name: $i18n.t("common.delete"),
          type: "danger",
          icon: "el-icon-delete",
          handleName: "deleteBatch", //点击时返回的标识
          isMultiple: true,
        },
        {
          // 导入文件
          render: (h, scope) => {
            // scope列表上选择的数据
            const uploadUrl = `${mesUrl}mesProcess/import`;
            return (
              <excelUpload
                action={uploadUrl}
                on={{
                  handleUploadError: (err) => {
                    // 失败的回调
                    console.log(err);
                  },
                  handleUploadSuccess: (res) => {
                    // vm.refresh();
                    _this.$refs.eleTable.handleReset();

                    //成功 的回调
                  },
                }}
              />
            );
          },
        },
        {
          name: $i18n.t("common.downloadTemplate"),
          type: "success",
          icon: "el-icon-download",
          handleName: "exportExcel", // 点击时返回的标识
        },

        {
          name: $i18n.t("mesProcess.assignStationExport"),
          type: "primary",
          icon: "el-icon-download",
          handleName: "export", //点击时返回的标识
          url: exportCellUrl,
          //auth: "auth:operlog:export", //权限字段
        },
      ],
    };
  },
};
// 行末按钮配置
export const rowConfig = [
  {
    name: $i18n.t("common.edit"),
    type: "primary",
    class: "row-btn-primary",
    handleName: "edit", // 点击时返回的标识
  },
  {
    name: $i18n.t("mesProcess.assignStation"),
    type: "success",
    icon: "el-icon-takeaway-box",
    handleName: "workcell",
    // auth: "auth:user:phenomenonreason", //权限字段
  },
  {
    name: $i18n.t("common.details"),
    type: "info",
    class: "row-btn-info",
    handleName: "detail", // 点击时返回的标识
  },
  {
    name: $i18n.t("common.delete"),
    type: "danger",
    class: "row-btn-danger",
    handleName: "delete", // 点击时返回的标识
  },
];

// 搜索条件配置
export const searchConfig = {
  data () {
    const _this = this;
    return {
      searchConfig: {
        inline: true,
        formDesc: {
          processTypeId: {
            type: "select",
            label: $i18n.t("mesProcess.processTypeId"),
            prop: {
              value: "id",
              text: "processTypeName",
            },
            options: async (data) => {
              const list = await getProcessTypeIdList();
              return list.data.result;
            },
          },
          workshopCode: {
            type: "select",
            label: $i18n.t("mesProcess.workshopName"),
            prop: {
              value: "modelingCode",
              text: "modelingName",
            },
            options: async (data) => {
              const params = {
                modelingCode: this.$store.getters.factoryCode,
                level: 4,
                modelingType: "0",
              };
              const list = await getLineCodeListNew(params);
              this.workshopList = list.data.result;
              return list.data.result;
            },
            // options: async (data) => {
            //   const params = {
            //     modelingCode: data.workshopCode,
            //     level: 5,
            //     modelingType: "0",
            //   };
            //   const list = await getLineCodeListNew(params);
            //   console.log(999, list);
            //   // this.workshopList = list.data.result;
            //   return list.data.result;
            // },
          },
          processCode: {
            type: "input",
            label: $i18n.t("mesProcess.processCode"),
          },
          processName: {
            type: "input",
            label: $i18n.t("mesProcess.processName"),
          },
        },
      },
    };
  },
};

var validatePass = (rule, value, callback) => {
  setTimeout(() => {
    if (!checkStr(value, "english-number")) {
      callback(new Error($i18n.t("mesProcess.rule8")));
    } else {
      callback();
    }
  }, 100);
};
// 新增/删除表单配置
export const formDescDialogMinxin = {
  data () {
    const self = this;
    return {
      formDescDialog: {
        span: 24,
        disabled: false,
        isShowSubmitBtn: true,
        rules: {
          processCode: [
            { validator: validatePass, trigger: ["change", "blur"] },
          ],
        },
        formDesc: {
          processTypeId: {
            type: "select",
            label: $i18n.t("mesProcess.processTypeId"),
            layout: 12,
            required: true,
            prop: {
              value: "id",
              text: "processTypeName",
            },
            options: async (data) => {
              const list = await getProcessTypeIdList();
              return list.data.result;
            },
          },
          processProperty: {
            type: "select",
            label: $i18n.t("mesProcess.processProperty"),
            layout: 12,
            required: true,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getProcessPropertyList();
              return list.data.result;
            },
          },
          processCode: {
            type: "input",
            label: $i18n.t("mesProcess.processCode"),
            layout: 12,
            required: true,
            disabled: (d) => !!d.id,
          },
          processName: {
            type: "input",
            label: $i18n.t("mesProcess.processName"),
            layout: 12,
            required: true,
          },

          isReportStart: {
            type: "select",
            label: $i18n.t("mesProcess.isReportStart"),
            layout: 12,
            required: true,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getYesOrNotList();
              return list.data.result;
            },
          },

          endReportModel: {
            type: "select",
            label: $i18n.t("mesProcess.endReportModel"),
            layout: 12,
            required: true,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getReportModelList();
              return list.data.result;
            },
          },
          processContent: {
            type: "input",
            label: $i18n.t("mesProcess.processContent"),
            layout: 12,
            required: false,
          },
          regularName: {
            type: "input",
            label: $i18n.t("mesProcess.regularName"),
            layout: 12,
            required: false,
          },
          workshopCode: {
            type: "select",
            label: $i18n.t("mesProcess.workshopName"),
            layout: 12,
            required: true,
            // disabled: true,
            attrs: {
              filterable: true,
            },
            prop: {
              value: "modelingCode",
              text: "modelingName",
            },
            options: async (data) => {
              const params = {
                modelingCode: this.$store.getters.factoryCode,
                level: 4,
                modelingType: "0",
              };
              const list = await getLineCodeListNew(params);
              this.workshopList = list.data.result;
              return list.data.result;
            },
            on: {
              change: (val) => {
                // debugger;
                if (!val) {
                  self.$set(self.formDataDialog, "workshopName", "");
                } else {
                  let obj = self.workshopList.find((item) => {
                    return item.modelingCode == val;
                  });
                  self.$set(self.formDataDialog, "workshopName", obj.modelingName);
                }
              },
            },
          },
          standardTime: {
            type: "number",
            label: $i18n.t("mesProcess.standardTime"),
            layout: 12,
            required: false,
            attrs: {
              min: 0,
              precision: 0,
            },
          },
          prepareTime: {
            type: "number",
            label: $i18n.t("mesProcess.prepareTime"),
            layout: 12,
            required: false,
            attrs: {
              min: 0,
              precision: 0,
            },
          },
          remark: {
            type: "textarea",
            label: $i18n.t("common.remark"),
            layout: 12,
            required: false,
          },
        },
      },
    };
  },
};

export const locationDialog = {
  data () {
    const that = this;
    return {
      modelingCode: "", // 线体下拉数据
      options: [], // 线体下拉内容
      formDescDialogCell: {
        span: 24,
        labelPosition: "top",
        formDesc: {
          workshopName: {
            type: "input",
            label: $i18n.t("mesProcess.workshopName"),
            disabled: true,
            layout: 6,
          },
          modelingCode: {
            type: "select",
            label: $i18n.t("mesProcess.lineName"), //"线体",
            layout: 12,
          },
          mesProcessCells: {
            type: "transfer",
            label: $i18n.t("mesProcess.station"),
            layout: 24,
            attrs: {
              titles: [
                $i18n.t("mesProcess.noAssignedStation"),
                $i18n.t("mesProcess.assignedStation"),
              ],
              props: {
                key: "modelingCode",
                label: "modelingName",
              },
            },
            options: [],
            on: {
              change: (val) => {
                that.mesProcessCellsChange(val);
              },
            },
            // options: async (data) => {
            //   const list = await getCellList()
            //   const result = []
            //   list.data.result.forEach((item) => {
            //     console.log(item)
            //     result.push({
            //       modelingCode: item.modelingCode + '-' + item.modelingName,
            //       modelingName: item.modelingCode + '-' + item.modelingName
            //     })
            //   })
            //   return result
            // }
          },

          table: {
            type: "input",
            label: $i18n.t("mesProcess.selectedStation"),
            layout: 24,
          },
        },
      },
    };
  },
  watch: {
    visibleCell: {
      handler (val) {
        if (!val) {
          this.modelingCode = "";
          this.$set(
            this.formDescDialogCell.formDesc.mesProcessCells,
            "options",
            []
          );
        } else {
          this.getLineCodeList();
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleDelete (index, row) {
      //判断删除的对象的线体，是否是正在分配的工位，如果存在，删除表格的同时，将已分配的工位也删除，保持同步
      const { lineCode, workCellCode, workCellName } = row;
      const { modelingCode, mesProcessCells } = this.formDataDialogCell;
      if (modelingCode == lineCode) {
        const data = mesProcessCells.filter(
          (val) => val != `${workCellCode}-${workCellName}`
        );
        this.$set(this.formDataDialogCell, "mesProcessCells", data);
      }
      this.tableData.splice(index, 1);
    },
    // 带查询按钮(点击查询再调接口)
    // 获取线体下拉数据
    getLineCodeList () {
      getLineCodeList({
        modelingCode: this.formDataDialogCell.workshopCode,
        level: 5,
      })
        .then((res) => {
          this.options = res.data.result || [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 根据线体获取工位数据
    searchLocation () {
      const lineCode = this.formDataDialogCell.modelingCode;
      getstationsByLineCode({
        modelingCode: lineCode,
        processCode: this.formDataDialogCell.processCode,
      }).then((res) => {
        const data = res.data.result || [];
        const list = data.map((item) => {
          return {
            ...item,
            modelingCode: item.modelingCode + "-" + item.modelingName,
            modelingName: item.modelingCode + "-" + item.modelingName,
          };
        });
        //查询表格下面是否存在相同线体的已分配工位

        let lineCodeList = [];
        this.tableData.forEach((val) => {
          if (val.lineCode == lineCode) {
            lineCodeList.push(`${val.workCellCode}-${val.workCellName}`);
          }
        });
        this.$set(this.formDataDialogCell, "mesProcessCells", lineCodeList);
        this.$set(
          this.formDescDialogCell.formDesc.mesProcessCells,
          "options",
          list
        );
      });
    },

    mesProcessCellsChange (val = []) {
      const tranferData = this.formDescDialogCell.formDesc.mesProcessCells
        .options;

      let list = tranferData.filter((item) => val.includes(item.modelingCode));
      const {
        processCode,
        processName,
        workshopName,
        workshopCode,
        modelingCode,
      } = this.formDataDialogCell;

      const lineItem = this.options.find(
        (item) => item.modelingCode == modelingCode
      );

      list.forEach((value) => {
        const [workCellCode, workCellName] = value.modelingCode.split("-");
        value = Object.assign(value, {
          processCode, //工序编码
          processName, //工序名称
          workshopName, //车间名称
          workshopCode, //车间编码
          lineCode: lineItem.modelingCode, //线体编码
          lineName: lineItem.modelingName, //线体名称
          isAdd: true, //是否新添加
          workCellCode, //工位编码
          workCellName, //工位名称
        });
      });
      //去除表格中选中线体的数据，

      const lineCode = this.formDataDialogCell.modelingCode;
      const tableData = this.tableData.filter(
        (val) => val.lineCode != lineCode
      );
      this.tableData = [...list, ...tableData];
    },
  },
};
